from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import JsonResponse
from celery_tasks.sms.tasks import send_sms
from rest_framework.viewsets import ModelViewSet
import re, random, os, base64, uuid
from .models import User
from .serializers import *
from rest_framework.views import APIView
from apps.utils.fastdfs.fastdfs_storage import FastDFSStorage
from TenSquare.settings.dev import BASE_DIR
# Create your views here.

# 短信验证码
class SMSCodeView(View):

    def get(self,request,mobile):
        user = User.objects.filter(mobile=mobile)
        if user:
            return JsonResponse({
                'code': 400,
                'errmsg': "手机号已存在"
            })

        # 连接redis
        conn = get_redis_connection('verify_code')

        # 判断60 秒之内是否发送过短信
        flag = conn.get("sms_flag_%s" % mobile)
        if flag:
            return JsonResponse({
                "code": 400,
                "errmsg": "请勿重复发送短信"
            })

        # 生成一个随机的短信验证码
        sms_code = "%6d" % random.randint(0, 999999)
        print(sms_code)

        p = conn.pipeline()
        try:
            p.setex("sms_%s" % mobile, 300, sms_code)
            # 添加标志位
            p.setex("sms_flag_%s" % mobile, 60, '1')

            p.execute()
        except Exception as e:
            return JsonResponse({
                "code": 400,
                "errmsg": "redis数据库访问失败"
            })
        # 调用云通讯发送短信
        send_sms.delay(mobile, sms_code)

        return JsonResponse({
            "code": 0,
            "errmsg": 'ok'
        })


class RegisterView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer



import json, re
# 用户中心和 修改
class InfoView(APIView):

    def get(self, request):
        user = User.objects.filter(id=request.user.id)
        serializer = UserSerializer(user,many=True)
        for i in serializer.data:
            return JsonResponse(dict(i))

    def put(self,request):
        rcv_data = json.loads(request.body.decode())

        src = rcv_data['avatar']
        # if src:
        #     User.objects.filter(id=request.user.id).update(avatar=None)
        #     return JsonResponse({'errmsg': '请重试'})

        # print(src)
        result = re.search("data:image/(?P<ext>.*?);base64,(?P<data>.*)", src, re.DOTALL)
        if result:
            '''判断是否第一次上传，个人档案头像只能上传一次'''
            ext = result.groupdict().get("ext")
            data = result.groupdict().get("data")

            # filepath = '/Users/mac/Desktop/'
            filepath = os.path.dirname(os.path.dirname(os.path.dirname(BASE_DIR)))

            # 2、base64解码
            img = base64.urlsafe_b64decode(data)
            filename = "{}.{}".format(uuid.uuid4(), ext)

            filepath_new = filepath + '/' + filename
            with open(filepath_new, "wb") as f:
                f.write(img)

            print(filepath_new)

            f = open(filepath_new, 'rb')
            ret = FastDFSStorage.save(self, name='name.jpg', content=f, max_length=None)
            url = FastDFSStorage.url(self, ret)

            # print(url)

            person_change = User.objects.filter(id=request.user.id).update(
                realname=rcv_data['realname'],
                sex=rcv_data['sex'],
                birthday=rcv_data['birthday'],
                website=rcv_data['website'],
                mobile=rcv_data['mobile'],
                email=rcv_data['email'],
                city=rcv_data['city'],
                address=rcv_data['address'],
                avatar=url,
            )
        else:
            person_change = User.objects.filter(id=request.user.id).update(
                realname=rcv_data['realname'],
                sex=rcv_data['sex'],
                birthday=rcv_data['birthday'],
                website=rcv_data['website'],
                mobile=rcv_data['mobile'],
                email=rcv_data['email'],
                city=rcv_data['city'],
                address=rcv_data['address'],
                avatar=rcv_data['avatar']
            )

        person = User.objects.filter(id=request.user.id)
        serializer = UserSerializer(person, many=True)
        for i in serializer.data:
            # print(dict(i))
            return JsonResponse(dict(i))



# 修改密码
class ChangePasswordView(View):
    def put(self,request):
        data = json.loads(request.body)
        new_pwd = data.get('new_pwd')

        if not new_pwd:
            return JsonResponse({'message': "修改失败", "type": "error"})

        try:
            request.user.set_password(new_pwd)
            request.user.save()
        except Exception as e:
            return JsonResponse({'message': "修改失败", "type": "error"})

        return JsonResponse({'message': "修改成功", "type": "success"})


# 添加好友关注和取消好友关注
class LikeView(APIView):
    def post(self,request, pk):
        user_obj = User.objects.get(id=request.user.id)
        fans_obj = User.objects.get(id=pk)

        user_obj.fans.add(fans_obj)

        return JsonResponse({
            'success': True,
            'message': '关注成功'
        })

    def delete(self,request, pk):
        user_obj = User.objects.get(id=request.user.id)
        fans_obj = User.objects.get(id=pk)

        user_obj.fans.remove(fans_obj)

        return JsonResponse({
            'success': True,
            'message': '取消关注'
        })


# 头像上传
class AvatarView(View):
    def post(self, request):

        rec_data = request.FILES.get('img')

        # FastDFSStorage.exists(data)

        ret = FastDFSStorage.save(self, name='name.jpg', content=rec_data, max_length=None)
        url = FastDFSStorage.url(self, ret)

        return JsonResponse({
            'imgurl': url
        })


from django.http import response
# 前端副文本编辑器上传图片
class CommonView(View):
    def post(self, request):
        '''前端副文本编辑器上传图片'''
        rec_data = request.FILES.get('upload')

        # FastDFSStorage.exists(data)

        ret = FastDFSStorage.save(self, name='name.jpg', content=rec_data, max_length=None)
        image_url = FastDFSStorage.url(self, ret)
        url = "http://127.0.0.1:8080/upload_success.html?image_url=" + image_url + "&CKEditorFuncNum=1"

        # http://127.0.0.1/upload_success.html?image_url=http://47.92.144.35:443/group1/M00/00/00/rBACxl3ggw2AZ1CbAAAo5jLCaQc72
        # 73744&CKEditorFuncNum=1
        return response.HttpResponseRedirect(url);


from rest_framework.generics import UpdateAPIView
# 修改擅长技术
class UpdatelabelView(UpdateAPIView):
    serializer_class = UpdateLabelSerializer
    # permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user